


import httptool from './zry.httptool';

export default {
	apiUrl:{
		listTree:'category/listTree', 
		getTypeBannner:'bannner/getTypeBannner', //获取广告
		listTop:'category/listTop', //获取顶级类型
		getKnowLedgeOrder:'selects/getKnowLedgeOrder',//获取知识库排序
		getProductByPage:'product/getProductByPage', //获取产品
		getById:'product/getById', //获取产品详情页
		userConnection:'collection/userConnection', //收藏产品
		escConnection:'collection/escConnection', //取消收藏
		externalLinks:'externalLinks/list', //外部链接
		browseRecord:'browseRecord/add', //浏览记录
		downloadAdd:'product/downloadAdd' ,//下载记录
	},	
	constParam: {		
		url: {
			baseUrl: utils.baseUrl, //url地址参数
			publicUrl:utils.publicUrl, //外部url,token登录后端
		}
	},
	isLogin:function(){
		var that = this;		
		//判断本地是否有缓存
		if(utils.getStorage('token')){
			console.log('token存在')			
			that.cheeckToken(utils.getStorage('token'),that.isLogin)
		}else{
			console.log('token不存在')
			//获取url的token
			var hash = window.location.hash
			var index = hash.indexOf('?token=')
			if(index>0){
				var token = hash.substring(index+7,hash.length)
				console.log(hash,index,token)
				//检测token是否有效
				that.cheeckToken(token,that.isLogin)				
			}else{
				console.log('去登陆')
			}
		}
	},
	cheeckToken:function(token,scall){
		var that = this;
		$.ajax({
			type: 'POST',
			url: this.constParam.url.publicUrl + "/auth/check",
			dataType: 'json',
			async: false,
			crossDomain: true,
			headers: {
				"Authorization" : token,
				'Access-Control-Allow-Origin': '*',
				"AppId":"1f37843951d64013ad98a968877e5696"
			},
			success: function(data) {						
				if(data.succeed){
					console.log('token有效')
					utils.setStorage('token',token)
					utils.setStorage('userinfo',data.data)
					console.log(data) 
				}else{
					that.reFresh(token,scall)
					console.log('token过期了')
				}
			},
			error: function(xhr, textStatus, errorThrown) {
				console.log(xhr.status);
				return;
				if(xhr.status == 401) {
					self.tips = "Network Error";
				} else if(xhr.status == 403) {
					self.tips = "Network Error";
				} else {
					self.tips = "Network Error";
				}
			}
		});				
	},
	reFresh:function(token,scall){
		var that = this;
		$.ajax({
			type: 'POST',
			url: that.constParam.url.publicUrl + "/auth/refresh",
			dataType: 'json',
			async: false,
			crossDomain: true,
			headers: {
				"Authorization" : token,
				'Access-Control-Allow-Origin': '*',
				"AppId":"1f37843951d64013ad98a968877e5696"
			},
			success: function(data) {	
				console.log(data)
				if(data.succeed){
					console.log('刷新')
					console.log(data) 
					var new_token = data.data.token	
					utils.setStorage('token',new_token)
					if(scall){
						console.log(scall)
						scall.bind(that)()
					}					
				}else{
					console.log('去登陆')
				}
			},
			error: function(xhr, textStatus, errorThrown) {
				console.log(xhr.status);
				return;
				if(xhr.status == 401) {
					self.tips = "Network Error";
				} else if(xhr.status == 403) {
					self.tips = "Network Error";
				} else {
					self.tips = "Network Error";
				}
			}
		});				
	},
	hasToken:function(){
		//获取url的token
		var hash = window.location.hash
		var index = hash.indexOf('?token=')
		if(index>0){
			var token = hash.substring(index+7,hash.length)
			utils.setStorage('token',token)
			return true;
		}else if(utils.getStorage('token')){
			return true;
		}else{
			//没有登录，跳到登录页面
			console.log('去登陆')
//			window.location.href = 'http://120.25.212.63:8088/testprj/electric/PC/static/login/'
			window.location.href = 'http://119.23.172.36/pc/static/login/'

		}
	},
	ajaxPost: function(url, data, successback, errorback, isasync, head) {
		var that = this;
//		console.log(utils.getStorage('token'))
		//判断本地是否存在token		
		if(that.hasToken()){
			$.ajax({
				type: 'POST',
				url:  that.constParam.url.baseUrl+url,
				dataType: 'json',
				async: false,
				data: JSON.stringify(data),
				crossDomain: true,
				traditional: true, //传递数组
				contentType: "application/json; charset=utf-8",
				headers: {
					"Authorization": utils.getStorage('token'),
					"AppId":"1f37843951d64013ad98a968877e5696"
				},
				success: function(data) {
					if(data.succeed){
						if(successback)
							successback.bind(this)(data)
					}else{
						if(data.code==1004){
							console.log(data)
//							window.location.href = 'http://192.168.10.92:8020/DianWang_pc/static/login/index.html'
							window.location.href = 'http://119.23.172.36/pc/static/login/'
						}
					}
					
				}
			})
		}
	},
	
	setCookie: function(name, value, hour) {
		var root = zry.util.siteUrl();
		if(hour) {
			var exp = new Date();
			exp.setTime(exp.getTime() + 1000 * 60 * 30);
			document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + "; path=" + root;
		} else {
			document.cookie = name + "=" + escape(value) + "; path=" + root;
		}
	},
	getCookie: function(name) {
		var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

		if(arr = document.cookie.match(reg))
			return unescape(arr[2]);
		else
			return null;
	},
	//保存到本地数据
	setStorage: function(k, v) {
		if(typeof(v) == "object")
			v = JSON.stringify(v);
		window.sessionStorage[k] = v;

	},
	//获取本地数据
	getStorage: function(k) {
		var v = window.sessionStorage[k];
		if(/^[{|[].+[}|\]]$/.test(v))
			v = JSON.parse(v);
		return v;
	},
	//删除本地数据
	removeStorage: function(k) {
		return window.sessionStorage.removeItem(k);
	},
	utils: {
		//格式化时间
		formatTime: function(str) {
			if(str == null || str == "")
				return "";
			var date = new Date(str);
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			var day = date.getDate();

			var hour = date.getHours();
			var minute = date.getMinutes();
			var second = date.getSeconds();

			return [year, month, day].map(this.formatNumber).join('/') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
		},
		formatNumber: function(n) {
			n = n.toString();
			return n[1] ? n : '0' + n;
		},
		//计算分页
		page: function(that, curPage, totalCount) {
			that.page.pageIndex = curPage;
			if(totalCount % that.page.pageSize == 0)
				that.page.pageTotal = totalCount / that.page.pageSize;
			else
				that.page.pageTotal = parseInt(totalCount / that.page.pageSize) + 1;
		},
		//跳转url
		setUrl: function(url, obj, isNew) {
			if(obj)
				url = url + "?request=" + encodeURI(JSON.stringify(obj));
			if(!isNew) {
				window.location.href = url;
			} else {
				window.open(url);
			}

		},
		//得到url参数
		getUrl: function() {
			var url = location.search
			if(url.length > 9) {
				var obj = decodeURI(url.substring(9, url.length))
				return JSON.parse(obj);
			} else
				return null;
		},
		//获取目标元素
		get_target_dom: function(dom, targetClass) {
			while(!dom.hasClass(targetClass)) {
				dom = dom.parent()
				//				console.log(dom)
			}
			return dom;
		},
		//拼接图片前缀
		imagePrefix: function(image, defaultImage, num) {
			if(image != null) {
				if(!num) {
					return globalData.constParam.url.baseUrl + "/" + image;
				} else {
					return globalData.constParam.url.baseUrl_2 + "/" + image;
				}
			}

		},
		//空值 默认值
		notNullDefaulst: function(v, defValue) {
			if(v == null || v == '' || v == 'null')
				v == defValue;
			return v;
		},
		//图片加载事件
		img_onload: function(ev, rate) {
			var dom = ev.target
			var ww = dom.width
			var hh = dom.height
			//			console.log(ww,hh)
			var p = rate || 1
			//			var p_w = $(dom).parent().width()
			//			var p_h = $(dom).parent().height()
			if(ww / hh > p) {
				$(dom).css({
					'height': '100%',
					'width': 'auto'
				})
			} else {
				$(dom).css({
					'height': 'auto',
					'width': '100%'
				})

			}
		},
		//图片加载错误事件
		imgLoadErr: function(ev) {
			//			console.log(ev.target)
			ev.target.src = 'imgs/icon.jpg'
		},
		//滚动到顶部
		scrool_top: function() {
			//			var x = document.body.scrollTop || document.documentElement.scrollTop;
			setTimeout(function() {
				window.scrollTo(0, 0);
			}, 50)
		},
		//返回上一页
		go_back: function() {
			window.history.go(-1)
		}
	}
};